package com.service;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SeckillService {

    @Autowired
    private AmqpTemplate amqpTemplate;  //发消息用的

    @Autowired
    private RedisTemplate  redisTemplate; //写读库存

    @Autowired
    private RedissonClient  redissonClient; //分布式锁

    /**
     *
     * @param uid  用户编号
     * @param goodsId 商品编号
     * @return
     */
    public String  go(int uid, int goodsId) throws InterruptedException {
        //获取分布式锁对象
        RLock  rLock = redissonClient.getLock("miaosha");
        //最多等3000毫秒，3000毫秒后还没有获取锁，则f=false
        //2000毫秒会自动释放锁
        //redisTemplate.boundValueOps("kuchun").set("3");
        boolean f = rLock.tryLock(3000,2000,TimeUnit.MILLISECONDS);
        if (f){
             //判断库存是否够
            Integer kuchun = Integer.parseInt( redisTemplate.boundValueOps("kuchun").get().toString());
            System.out.println("当前库存是:"+kuchun);
            if (kuchun>0){
                 kuchun--;
                 redisTemplate.boundValueOps("kuchun").set(kuchun.toString());
                 Map map = new HashMap();
                 map.put("uid",uid);
                 map.put("goodsId",goodsId);
                 amqpTemplate.convertAndSend("sunjob_exchange",null,map);
            }
            else{
                return "对不起，此商品已卖光了";
            }

        }else{
           return "当前用户过多，请稍候再试";
        }
        rLock.unlock();
        return "秒杀成功";
    }

}
